package com.journaldev.spring;

import java.sql.Date;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.journaldev.spring.dao.DistrictDAOImpl;
import com.journaldev.spring.model.Medicine;
import com.journaldev.spring.model.Patient;
import com.journaldev.spring.model.Prescription;
import com.journaldev.spring.model.PrescriptionMedicine;
import com.journaldev.spring.service.MedicineService;
import com.journaldev.spring.service.PatientService;
import com.journaldev.spring.service.PrescriptionMedicineService;
import com.journaldev.spring.service.PrescriptionService;
import com.journaldev.spring.util.SimpleDateTimeEditor;
import com.journaldev.spring.util.SimplePatientEditor;
import com.journaldev.spring.util.SimplePrescriptionMedicineEditor;

@Controller
public class PrescriptionController {
	
	private static final Logger logger = LoggerFactory.getLogger(PrescriptionController.class);
	
	private PrescriptionService prescriptionService;
	
	private PatientService patientService;
	
	private MedicineService medicineService;
	
	private PrescriptionMedicineService prescriptionMedicineService;
	
	@Autowired(required=true)
	@Qualifier(value="prescriptionMedicineService")
	public void setPrescriptionMedicineService(
			PrescriptionMedicineService prescriptionMedicineService) {
		this.prescriptionMedicineService = prescriptionMedicineService;
	}

	@Autowired(required=true)
	@Qualifier(value="medicineService")
	public void setMedicineService(MedicineService medicineService) {
		this.medicineService = medicineService;
	}

	@Autowired(required=true)
	@Qualifier(value="patientService")
	public void setPatientService(PatientService patientService) {
		this.patientService = patientService;
	}

	@Autowired(required=true)
	@Qualifier(value="prescriptionService")
	public void setPrescriptionService(PrescriptionService prescriptionService) {
		this.prescriptionService = prescriptionService;
	}
	
	@InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        binder.registerCustomEditor(Date.class, new SimpleDateTimeEditor());
        binder.registerCustomEditor(Patient.class, new SimplePatientEditor(patientService));
        binder.registerCustomEditor(Set.class, new SimplePrescriptionMedicineEditor(medicineService));
    }
	
	@RequestMapping(value = {"/prescriptions"}, method = RequestMethod.GET)
	public String listPrescriptions(HttpServletRequest request,Model model) {
		model.addAttribute("prescription", new Prescription());
		//UserInfo user = (UserInfo) request.getSession().getAttribute("USER_LOGIN");
		model.addAttribute("listPrescriptions", this.prescriptionService.listPrescription());
		model.addAttribute("listPatients", this.patientService.listPatient());
		model.addAttribute("listMedicines", this.medicineService.listMedicine());
		return "prescription";
	}
	
	@RequestMapping(value = {"/prescription/add"}, method = RequestMethod.POST)
	public String addPrescription(@ModelAttribute("prescription") Prescription p,  BindingResult result, Model model, RedirectAttributes redirectAttrs) {
		logger.info("Start addPrescription");
		if(result.hasErrors()) {
			logger.error("Error addPrescription");
			model.addAttribute("message", "thêm đơn thuốc không thành công !!!");
			return "redirect:/prescriptions";
		}
		if(p.getId() != 0) {
			Iterator<PrescriptionMedicine> iterator = p.getPrescriptionMedicine().iterator();
			while(iterator.hasNext()) {
				PrescriptionMedicine pres = iterator.next();
				pres.setPrescription(p);
			}
			this.prescriptionService.updatePrescription(p);
			redirectAttrs.addFlashAttribute("message", "cập nhật đơn thuốc thành công id =" + p.getId());
		} else {
			// iterate through prescriptionmedicine set
			
			Iterator<PrescriptionMedicine> iterator = p.getPrescriptionMedicine().iterator();
			while(iterator.hasNext()) {
				PrescriptionMedicine pres = iterator.next();
				pres.setPrescription(p);
			}
			
			this.prescriptionService.addPrescription(p);
			redirectAttrs.addFlashAttribute("message", "thêm đơn thuốc thành công");
		}
		model.asMap().clear();
		logger.info("End addPrescription");
		return "redirect:/prescriptions";
	}
	
	@RequestMapping("/prescription/edit/{id}")
    public String editPrescription(@PathVariable("id") int id, Model model){
        model.addAttribute("prescription", this.prescriptionService.getPrescriptionById(id));
        model.addAttribute("listPrescriptions", this.prescriptionService.listPrescription());
		model.addAttribute("listPatients", this.patientService.listPatient());
		model.addAttribute("listMedicines", this.medicineService.listMedicine());
		return "prescription";
    }
	
	@RequestMapping("/prescription/remove/{id}")
    public String removePrescription(@PathVariable("id") int id){
		logger.info("Start removePrescription");
		Prescription p = this.prescriptionService.getPrescriptionById(id);
		if(p != null) {
			Iterator<PrescriptionMedicine> iterator = p.getPrescriptionMedicine().iterator();
			while(iterator.hasNext()) {
				PrescriptionMedicine preMed = iterator.next();
				Medicine med = preMed.getMedicine();
				this.prescriptionMedicineService.removePrescriptionMedicine(p, med);
				//p.getPrescriptionMedicine().remove(preMed);
			}
		}
		p.setPrescriptionMedicine(null);
		this.prescriptionService.updatePrescription(p);
        this.prescriptionService.removePrescription(p);
        logger.info("End removePrescription");
        return "redirect:/prescriptions";
    }
	
}
